define(['app', 'pagination', 'datetime', 'js/service/agupload','floatlayer'], function(appCRM) {
    'use strict';
    /*后台客户资源查看*/
    appCRM.controller('Customer', function($scope, dataFactoryCRM, $q, $timeout, crmConst, AgUpload, crmParam) {
        $scope.customer_list = null;
        $scope.search_param = {audit:-1,customer:'',sales:'',start_time:'',end_time:'',export:0};
        $scope.import_pays_error = "";
        $scope.import_pays_step = 0;
        $scope.customerPage = { pageAll:1, pageNow:1, pageSize:$scope.psize, k: 3892, pageName: 'customerPage' };
        $scope.combine_data = {from:false,to:false };
        $scope.dataStatus = {};
        
        //教育和工作
        $scope.educationTypes = crmConst.EDUCATION;
        $scope.careerTypes = crmConst.CAREER;
        $scope.dataStatus = crmParam.get( 'customerStatus');

        $scope.import_paysUser = function(){
            $scope.import_pays_step = 1;
            $scope.import_data = {};
            $scope.import_pays_error = '';

            $('.import.pay.user').modal({
                observeChanges: true,
                closable:false,
                onApprove:function(){
                    $scope.import_pays_step = 2;
                    return false;
                },
            }).modal('show');
        };

        $scope.$watch('search_param.audit', function(newV, oldV){
            if (newV != oldV) { //如果变化前后数据不一样就加载
                $scope.search();
            }
        });

        $scope.search = function(){
            $scope.customerPage.pageNow = 1;
            $scope.search_param.export = 0;
            $scope.getDataList();
        };

        $scope.enterSearch = function( evt ){
            if (evt && evt.keyCode==13) {
                 $scope.search();
            }
        };

        //客户池导入模板
        $scope.importTemplate = function(){
            dataFactoryCRM.getDataByAPI('customer/index?template_export=1',true).then( function(d ) {
                if( d && d.rcode ){
                    AgUpload.downExcel(d.data.view_path, "客户池导入表");
                }
            });
        }
        //Excel导出
        $scope.export_list = function(){
            var downParam = $scope.search_param;
            downParam.export = 1;
            dataFactoryCRM.getDataByAPI('customer/index?' + $.param( downParam ) ,true).then( function(d ) {
                $scope.search_param.export = 0;
                if( d && d.rcode ){
                    AgUpload.downExcel(d.data.view_path, "客户池数据记录表");
                }
                else{
                    $('<div class="ui small modal modal2" style="text-align: center;"><div class="header">提示</div><div class="content"><i class="huge red warning outline icon"></i>' +
                    '<p style="padding-top: 15px;">'+d.msg+'</p>' +'</div></div>'
                ).modal('show');
                }
            });
        };

        $scope.safeApply = function (fn) {
            var phase = this.$root.$$phase;
            if (phase == '$apply' || phase == '$digest') {
                if (fn && (typeof (fn) === 'function')) {
                    fn();
                }
            } else {
                this.$apply(fn);
            }
        };

        //客户合并
        $scope.combineCustomer = function( $_from, $_to ){
            function _combine( _from, _to ){
                var deferred = $q.defer();
                if (_from && _to) {
                    $scope.busy = dataFactoryCRM.postDataByAPI('customer/combine',{from:_from,to:_to})
                        .then(function(d) {
                            deferred.resolve(d);
                        });
                } else
                    deferred.reject('参数提交错误');
                return deferred.promise;
            }

            function _err( _msg ){
                $scope.safeApply( function(){
                    $scope.combine_error = _msg ; });
                $timeout(function(){
                     $scope.combine_error = '';
                }, 2000);
            }

            $scope.combine_data.from = '';
            $scope.combine_data.to = '';
            $('.ui.combine').modal({
                autofocus:false,
                closable:false,
                onApprove:function(){
                     if( $scope.combine_data.from && $scope.combine_data.to ){
                        if( $scope.combine_data.from == $scope.combine_data.to ){
                            _err ( "合并客户与被合并客户不能是同一个人" );
                            return false;
                        }
                        else{
                            _combine( $scope.combine_data.from, $scope.combine_data.to ).then(function( d ){
                                if( d && d.rcode ){
                                    $('.ui.combine').modal("hide");
                                    $('<div class="ui small modal modal1" style="text-align: center;"><div class="header">提示</div><div class="content"><i class="huge green check circle outline icon"></i>' +
                                        '<p style="padding-top: 15px;">合并成功</p>' +'</div></div>'
                                    ).modal('show');
                                    $timeout(function(){
                                        $scope.getDataList();
                                    }, 5);
                                    return true;
                                }
                                else
                                    _err( d.msg );
                            },
                            function( err ){
                                _err( "合并客户接口请求失败" );
                            });
                        }
                    }
                    else{
                        _err( "合并客户参数提交错误" );
                        return false;
                    }
                    return false;
                },
            }).modal('show');
        };

        //批量导入错误显示
        $scope.import_file_error = function ( _msg ){
            $scope.import_pays_error = _msg ;
            $timeout(function(){
                $scope.import_pays_error = '';
            }, 5000);
        };

        //导入解析结果拖动
        $scope.drag_drop = function( _data ){
            if( 'drop' == _data.op    ){
                var k_from = _data.from;
                var k_to = _data.to;
                if( $scope.import_data.fusion[k_from]['key'] == $scope.import_data.fusion[k_to]['key'] ){
                    $scope.import_data.fusion[k_to]['sub_user'].push( $scope.import_data.fusion[k_from] );
                    delete $scope.import_data.fusion[k_from];
                }
                else{
                    // not the same person
                }
            }
            else if( 'remove' == _data.op ){
                var k_from = _data.from;
                var k = _data.k;
                var item = $scope.import_data.fusion[k_from]['sub_user'].filter( function( obj ) {
                     return obj.k == k;
                });
                item = item[0];
                var  k_index = 0;
                for(var i=0;i< $scope.import_data.fusion[k_from]['sub_user'].length; i++ ){
                    if( $scope.import_data.fusion[k_from]['sub_user'][i]['k'] == k ){
                        k_index = i;
                        break;
                    }
                }
                $scope.import_data.fusion[k_from]['sub_user'].splice(k_index,1);
                $scope.import_data.fusion[k] = item;
            }
        };

        //导入解析结果编辑之后提交到后台
        $scope.import_data_save = function(){
            $scope.import_pays_step = 3;
            $scope.is_uploading = true;
            var _param = {'action':'save', 'data':JSON.stringify($scope.import_data)};
            dataFactoryCRM.postDataByAPI('Customer/pays_import', _param).then( function( d ) {
                $scope.import_ok =  0;
                $timeout(function() {  $scope.is_uploading = false;}, 0);
                if ( d.rcode == 1) {
                    $scope.import_data = {};
                    $scope.import_ok = d.ok;
                    $scope.import_data = d.data;
                    if( d.ok ){
                        $timeout(function() { $scope.getDataList();}, 100);
                    }
                }
                else{
                    $scope.import_data = {};
                    $scope.import_file_error("保存接口请求失败,"+d.msg);
                }
                },
                function( error ){
                    $scope.import_pays_step = 2;
                    $scope.import_file_error("保存数据失败" );
                }
            );
        };

        //导入Excel文件上传
        $scope.import_file_change = function( $fitem ){
            $scope.is_uploading = false;
            if( !$fitem ){
                //没有选择文件
                //$scope.import_file_error( "选择文件格式错误" );
            }
            else{
                $timeout(function(){
                    $scope.import_pays_error = '';
                });
                $scope.is_uploading = true;
                AgUpload.add( $fitem );
                AgUpload.setUrl('customer/pays_import');
                AgUpload.param_add('action','upload');
                AgUpload.start().then( function( d ){
                    $scope.is_uploading  = false;
                    if( d && d.rcode ){
                        $scope.import_pays_error = '';
                        $scope.import_pays_step = 2;
                        $scope.import_data = d.data;
                        $scope.import_data.fusion_count = Object.keys($scope.import_data.fusion ).length;
                        $timeout(function(){$('.import.pay.user').modal('refresh');}, 0);
                    }
                    else{
                        $scope.import_file_error( d.msg );
                    }
                },
                function( err){
                    $scope.import_file_error("文件上传解析失败");
                });
            }

        };
        //合并客户查询
        $timeout(function(){
            $('.ui.combine .ui.dropdown')
              .dropdown({
                cache:false,
                message:{
                    noResults:'查询结果为空',
                },
                apiSettings: {
                  url: crmConst.BASE + crmConst.API + 'Customer/combine?q={query}'
                }
              });
        }, 0);

        //列表页数据
        $scope.getDataList = function() {
            var listParam = $scope.search_param;
            listParam['psize'] = $scope.customerPage.pageSize;
            listParam['p'] = $scope.customerPage.pageNow;
            var _url = 'Customer/index?' + $.param( listParam );
            dataFactoryCRM.getDataByAPI(_url, true).then(function(data) {
                if (data.rcode == 1) {
                    $scope.customer_list = data.data;
                    $scope.customerPage.dataCount = data.count;
                    if ( data.page > 1) {
                        $scope.customerPage.pageSize = data.psize;
                        $scope.customerPage.pageAll = data.page;
                        $scope.customerPage.pageNow = data.p;
                    } else {
                        $scope.customerPage.pageSize = $scope.psize;
                        $scope.customerPage.pageAll = 1;
                        $scope.customerPage.pageNow = 1;
                    }
                }
            });
        }
        //初始化页面显示数据（如果是新弹出独立窗口则从父窗口获取）
        window.loadClientCacheToScope($scope, function(){
            $scope.getDataList();
        });
        

        //file import watcher
        $scope.$watch('import_pays_file', function(newValue, oldValue){
            if( newValue == oldValue ) return true;
        },true);

        $scope.$on('pay_drag_drop', function(event,data ){
            if( data ){
                $scope.drag_drop( data );
            }
        });
    })
    .directive('userStatus', function( crmParam ) {
            var _uStatus =  crmParam.get( 'customerStatus');
            var uStatus = {};
            _uStatus.forEach(function(v){
                uStatus[v.status] = v.statusTitle;
            });
            return {
                restrict: 'A',
                template: "{{status}}",
                link: function(scope, element, attrs) {
                    if (attrs.status&& attrs.status in uStatus)
                        scope.status = uStatus[attrs.status];
                }
            };
        })
        .directive('payConbine', ['$timeout', function( $timeout ) {
        var MSG_NAME = 'pay_drag_drop';
        return {
            restrict: 'A',
            controller:['$scope',function( $scope ){
                //取消合并
                $scope.drag_remove = function(from, key ){
                    var _param = {'op':'remove','from':from,'k':key };
                    $scope.$emit( MSG_NAME , _param );
                }
            }],
            link: function (scope, ele, attrs) {
                $(ele).attr('draggable', true );

                ele.on('dragstart', function(ev) {
                    ev = ev.originalEvent || ev;
                    ev.dataTransfer.effectAllowed = "move";
                    $(ele).siblings().removeClass("active");
                    $(ele).addClass("active");
                    if( !$(ev.target).attr('draggable') ){
                        window.getSelection().removeAllRanges();
                        return false;
                    }
                    ev.dataTransfer.setData("Text",attrs.v );
                    ev.stopPropagation();
                });

                ele.on('selectstart', function() {
                    if (this.dragDrop) this.dragDrop();
                });

                ele.on('dragend',function( ev ){
                    ev = ev.originalEvent || ev;
                    ev.stopPropagation();
                    $timeout(function() { $(ele).removeClass("active");}, 0);
                });

                ele.on('dragover', function( ev ){
                    ev = ev.originalEvent || ev;
                    ev.stopPropagation();
                    return false;
                });

                ele.on('drop', function(ev) {
                    ev = ev.originalEvent || ev;
                    var key = ev.dataTransfer.getData('Text');
                    var key2 = attrs.v;
                    if( key == key2  ){
                        // key not same
                    }
                    else if( key != key2 ){
                        var _param = {'op':'drop','from':key,'to':key2 };
                        scope.$emit( MSG_NAME , _param );
                    }
                    ev.preventDefault();
                    ev.stopPropagation();
                    return false;
                });
            }
        };
    }]);
});
